package cn.hznc.controller.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hznc.configuration.SystemInit;
import cn.hznc.constant.CommonConstant;
import cn.hznc.constant.UrlConstant;
import cn.hznc.controller.service.QuerySqlServerService;
import cn.hznc.controller.service.inventory.InventoryLocationService;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.inventory.InBoundOrOutBoundTimeReq;
import cn.hznc.exception.ToolLifeCycleException;
import cn.hznc.mapper.*;
import cn.hznc.repository.IcabinetRecordRepository;
import cn.hznc.repository.InventoryLocationRespository;
import cn.hznc.repository.ToolForkInfoRespository;
import cn.hznc.repository.ToolParamCacheRepository;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.UUIDUtil;
import cn.hznc.vo.LocationNumberVo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：Administrator
 * @Date：2023/5/16 10:38
 */
@Component
@Slf4j
public class InventoryTask {

    @Resource
    private ToolInventoryLocationMapper toolInventoryLocationMapper;

    @Resource
    private ToolInventoryLocationHistoryMapper toolInventoryLocationHistoryMapper;

    @Resource
    private IcabinetConfigMapper icabinetConfigMapper;

    @Resource
    private InventoryLocationService inventoryLocationService;

    @Resource
    private InventoryLocationRespository inventoryLocationRespository;

    @Resource
    private ToolForkInfoRespository toolForkInfoRespository;

    @Resource
    private ICabinetRecordMapper iCabinetRecordMapper;

    @Resource
    private IcabinetRecordRepository icabinetRecordRepository;

    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;

    @Resource
    private ConfigurationMapper configurationMapper;

    @Resource
    private QuerySqlServerService querySqlServerService;

    @Resource
    private ProductionBomMapper productionBomMapper;

    @Resource
    private ProductionMapper productionMapper;

    @Resource
    private ToolParamCacheRepository toolParamCacheRepository;

    @Scheduled(cron = "0 30 23 * * ? ")
    public void inventorySnapshotTask() {
        //每晚11点半做库存快照
        List<ToolInventoryLocationEntity> toolInventoryLocationEntities = toolInventoryLocationMapper.selectList(new QueryWrapper<>());
        List<ToolInventoryLocationHistoryEntity> entityList = toolInventoryLocationEntities.stream().map(this::transfrom).collect(Collectors.toList());
        toolInventoryLocationHistoryMapper.insertBatchSomeColumn(entityList);
    }

//    @Scheduled(cron = "0 45 23 * * ? ")
//    public void syncSmartICabinetDataFeed() {
//        List<IcabinetConfigEntity> icabinetConfigEntities = icabinetConfigMapper.selectList(new QueryWrapper<>());
//        if (CollectionUtil.isNotEmpty(icabinetConfigEntities)) {
//            //对接G1-G5智能柜的数据
//            icabinetConfigEntities.forEach(icabinetConfigEntity -> {
//                Map<String, String> heardMap = new HashMap<>();
//                Map<String, Object> contentMap = new HashMap<>();
//                contentMap.put("Uid", "");
//                contentMap.put("Code", UrlConstant.ICABINET_FEEDING_SYNC_CODE);
//                contentMap.put("Digest", icabinetConfigEntity.getDigest());
//                //请求参数data
//                Map<String, Object> dataMap = new HashMap<>();
//                dataMap.put("Gtype", UrlConstant.ICABINET_FEEDING_SYNC_GTYPE);
//                //获取时间map
//                QueryWrapper<ConfigurationEntity> wrapper = new QueryWrapper<>();
//                wrapper.eq("configure_key" , CommonConstant.ICABINET_PULL_Feed_TIME);
//                ConfigurationEntity configurationEntity = configurationMapper.selectOne(wrapper);
//                SimpleDateFormat sdf = new SimpleDateFormat();
//                try {
//                    Date date = CommonUtil.parseDate(configurationEntity.getConfigureValue());
//                    if(date.compareTo(new Date())>0){
//                        inventoryLocationRespository.updateDate(CommonConstant.ICABINET_PULL_Feed_TIME , sdf.format(new Date()));
//                    }
//                    dataMap.put("Date1", CommonUtil.transferDate(date));
//                } catch (ParseException e) {
//                    log.error(e.getMessage());
//                }
////                Map<String, String> dateMap = CommonUtil.minusTime24h();
////                dataMap.put("Date1", dateMap.get("Date1"));
////                dataMap.put("Date2", dateMap.get("Date2"));
//                dataMap.put("Date2", CommonUtil.transferDate(new Date()));
//                contentMap.put("Data", JSONObject.toJSONString(dataMap));
//                //每晚11点45同步智能柜数据
//                String post = HttpUtil.post(UrlConstant.ICABINET_FEEDING_SYNC_URL, contentMap);
//                //String post = CommonUtil.postMap(UrlConstant.ICABINET_FEEDING_SYNC_URL , heardMap , contentMap);
//                if (StringUtil.isNotEmpty(post)) {
//                    JSONObject jsonObject = JSONObject.parseObject(post);
//                    if (jsonObject.get("success").equals(true)) {
//                        Object o = jsonObject.get("data");
//                        JSONArray dataArray = JSONArray.parseArray(o.toString());
//                        if (ObjectUtil.isNotNull(dataArray)) {
//                            for (Object oneRecordObject : dataArray) {
//                                JSONArray oneRecord = JSONArray.parseArray(oneRecordObject.toString());
//                                String partno = (String) oneRecord.get(7);
//                                //设置入库库位
//                                List<LocationNumberVo> ids = inventoryLocationRespository.qryFeedLocationNum("A002", partno);
//                                if (CollectionUtil.isNotEmpty(ids)) {
//                                    List<LocationNumberVo> result = findLocationNumber(ids , (Integer) oneRecord.get(16));
//                                    if(CollectionUtil.isNotEmpty(result)){
//                                        result.forEach(locationNumberVo -> {
//                                            InBoundOrOutBoundTimeReq inBoundOrOutBoundTimeReq = new InBoundOrOutBoundTimeReq();
//                                            inBoundOrOutBoundTimeReq.setNumber(locationNumberVo.getNumber());
//                                            inBoundOrOutBoundTimeReq.setBz((String) oneRecord.get(3));
//                                            inBoundOrOutBoundTimeReq.setInventoryLocationId(locationNumberVo.getId());
//                                            inBoundOrOutBoundTimeReq.setOperator((String) oneRecord.get(2));
//                                            inBoundOrOutBoundTimeReq.setPartno(partno);
//                                            inBoundOrOutBoundTimeReq.setPartType(toolForkInfoRespository.selectPartTypeByPartno(partno));
//                                            inBoundOrOutBoundTimeReq.setCreateTime((Date) oneRecord.get(1));
//                                            try {
//                                                inventoryLocationService.inboundLocationTool(inBoundOrOutBoundTimeReq);
//                                            } catch (ToolLifeCycleException e) {
//                                                log.error("sync icabinet stock error =>{}" + e.getMsg() + new Date());
//                                            }
//                                        });
//                                    }
//
//                                }
//                            }
//                        }
//                    }
//                }
//            });
//        }
//    }
//
//
//
//    @Scheduled(cron = "0 45 23 * * ? ")
//    public void syncSmartICabinetDataReclaimer() {
//        List<IcabinetConfigEntity> icabinetConfigEntities = icabinetConfigMapper.selectList(new QueryWrapper<>());
//        if (CollectionUtil.isNotEmpty(icabinetConfigEntities)) {
//            //对接G1-G5智能柜的数据
//            icabinetConfigEntities.forEach(icabinetConfigEntity -> {
//                Map<String, Object> contentMap = new HashMap<>();
//                contentMap.put("Uid", "");
//                contentMap.put("Code", UrlConstant.ICABINET_FEEDING_SYNC_CODE);
//                contentMap.put("Digest", icabinetConfigEntity.getDigest());
//                //请求参数data
//                Map<String, Object> dataMap = new HashMap<>();
//                dataMap.put("Gtype", UrlConstant.ICABINET_RECLAIMING_SYNC_GTYPE);
//                //获取时间map
//                QueryWrapper<ConfigurationEntity> wrapper = new QueryWrapper<>();
//                wrapper.eq("configure_key" , CommonConstant.ICABINET_PULL_Reclaimer_TIME);
//                ConfigurationEntity configurationEntity = configurationMapper.selectOne(wrapper);
//                SimpleDateFormat sdf = new SimpleDateFormat();
//                try {
//                    Date date = CommonUtil.parseDate(configurationEntity.getConfigureValue());
//                    if(date.compareTo(new Date())>0){
//                        inventoryLocationRespository.updateDate(CommonConstant.ICABINET_PULL_Reclaimer_TIME , sdf.format(new Date()));
//                    }
//                    dataMap.put("Date1", CommonUtil.transferDate(date));
//                } catch (ParseException e) {
//                    log.error(e.getMessage());
//                }
////                Map<String, String> dateMap = CommonUtil.minusTime24h();
////                dataMap.put("Date1", dateMap.get("Date1"));
////                dataMap.put("Date2", dateMap.get("Date2"));
//                dataMap.put("Date2", CommonUtil.transferDate(new Date()));
////                Map<String, String> dateMap = CommonUtil.minusTime24h();
////                dataMap.put("Date1", dateMap.get("Date1"));
////                dataMap.put("Date2", dateMap.get("Date2"));
//                contentMap.put("Data", JSONObject.toJSONString(dataMap));
//                //每晚11点45同步智能柜数据
//                String post = HttpUtil.post(UrlConstant.ICABINET_RECLAIMING_SYNC_URL, contentMap);
//                //String post = CommonUtil.postMap(UrlConstant.ICABINET_RECLAIMING_SYNC_URL , heardMap , contentMap);
//                if (StringUtil.isNotEmpty(post)) {
//                    JSONObject jsonObject = JSONObject.parseObject(post);
//                    if (jsonObject.get("success").equals(true)) {
//                        List<List<Object>> data = (List<List<Object>>) jsonObject.get("data");
//                        if (CollectionUtil.isNotEmpty(data)) {
//                            data.forEach(oneRecord -> {
//                                String partno = (String) oneRecord.get(7);
//                                //设置入库库位
//                                List<LocationNumberVo> ids = inventoryLocationRespository.getByWarehouseIdAndPartno("A002", partno, (Integer) oneRecord.get(16));
//                                if (CollectionUtil.isNotEmpty(ids)) {
//                                    List<LocationNumberVo> result = findLocationNumber(ids , (Integer) oneRecord.get(16));
//                                    if(CollectionUtil.isNotEmpty(result)){
//                                        result.forEach(locationNumberVo -> {
//                                            InBoundOrOutBoundReq inBoundOrOutBoundReq = new InBoundOrOutBoundReq();
//                                            inBoundOrOutBoundReq.setNumber(locationNumberVo.getNumber());
//                                            inBoundOrOutBoundReq.setBz((String) oneRecord.get(3));
//                                            inBoundOrOutBoundReq.setInventoryLocationId(locationNumberVo.getId());
//                                            inBoundOrOutBoundReq.setOperator((String) oneRecord.get(2));
//                                            inBoundOrOutBoundReq.setPartno(partno);
//                                            inBoundOrOutBoundReq.setPartType(toolForkInfoRespository.selectPartTypeByPartno(partno));
//                                            try {
//                                                inventoryLocationService.outboundLocationTool(inBoundOrOutBoundReq);
//                                            } catch (ToolLifeCycleException e) {
//                                                log.error("sync icabinet stock error =>{}" + e.getMsg() + new Date());
//                                            }
//                                        });
//                                    }
//                                }
//                            });
//                        }
//                    }
//                }
//            });
//        }
//    }
//


    @Scheduled(cron = "0 45 23 * * ? ")
    public void syncSmartICabinetDataFeed() {
        syncSmartICabinetData("1" , CommonConstant.SYNC_ENTRY_FEED_TIME);
    }



    @Scheduled(cron = "0 50 23 * * ? ")
    public void syncSmartICabinetDataReclaimer() {
        syncSmartICabinetData("2" , CommonConstant.SYNC_ENTRY_RECLAIMER_TIME);
    }


    public List<LocationNumberVo> findLocationNumber(List<LocationNumberVo> idNumberMap , Integer number){
        List<LocationNumberVo> resultList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(idNumberMap) && ObjectUtil.isNotNull(number)){
            for (LocationNumberVo locationNumberVo : idNumberMap) {
                if(number > locationNumberVo.getNumber()){
                    //操作数量大于库位库存数量
                    LocationNumberVo locationNumberVo1 = new LocationNumberVo();
                    locationNumberVo1.setId(locationNumberVo.getId());
                    locationNumberVo1.setNumber(locationNumberVo.getNumber());
                    number = number - locationNumberVo.getNumber();
                    resultList.add(locationNumberVo1);
                }else{
                    LocationNumberVo locationNumberVo1 = new LocationNumberVo();
                    locationNumberVo1.setId(locationNumberVo.getId());
                    locationNumberVo1.setNumber(number);
                    resultList.add(locationNumberVo1);
                    break;
                }
            }

        }
        return resultList;
    }


    public void syncICabinetRecord(Integer flag) throws ParseException {
        Map<String, Object> contentMap = new HashMap<>();
        List<ToolForkInfoEntity> updateList = new ArrayList<>();
        List<ICabinetRecordEntity> insertList = new ArrayList<>();
        contentMap.put("Uid", "");
        contentMap.put("Code", UrlConstant.ICABINET_FEEDING_SYNC_CODE);
        contentMap.put("Digest", CommonConstant.ICABINET_DIGEST);
        //请求参数data
        Map<String, Object> dataMap = new HashMap<>();
        if (ObjectUtil.isNull(flag)) {
            flag = 0;
        }
        QueryWrapper<ConfigurationEntity> wrapper1 = new QueryWrapper<>();
        ICabinetRecordEntity existICabinetRecordEntity = null;
        String configurationKey = "";
        if (flag == 0) {
//            dataMap.put("Gtype", UrlConstant.ICABINET_FEEDING_SYNC_GTYPE);
//            wrapper1.eq("configure_key" , CommonConstant.SYNC_ENTRY_FEED_TIME);
            dataMap.put("Gtype", UrlConstant.ICABINET_FEEDING_SYNC_GTYPE);
            configurationKey = CommonConstant.SYNC_ENTRY_FEED_TIME;
            existICabinetRecordEntity = toolParamCacheRepository.getDateByType("加料单");
            //wrapper2.eq("")
        } else if(flag == 1){
            dataMap.put("Gtype", UrlConstant.ICABINET_RECLAIMING_SYNC_GTYPE);
            //wrapper1.eq("configure_key" , CommonConstant.SYNC_ENTRY_RECLAIMER_TIME);
            configurationKey = CommonConstant.SYNC_ENTRY_RECLAIMER_TIME;
            existICabinetRecordEntity = toolParamCacheRepository.getDateByType("取料单");
        }
//        ConfigurationEntity configurationEntity = configurationMapper.selectOne(wrapper1);
//        String startTime = configurationEntity.getConfigureValue();
        String startTime = SystemInit.configurationMap.get(CommonConstant.SYNC_ENTRY_FEED_TIME).toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //放到出入库时统一更新该数据
//        if (flag == 0) {
//            inventoryLocationRespository.updateDate(CommonConstant.ICABINET_PULL_Feed_TIME , sdf.format(new Date()));
//        } else if(flag == 1){
//            inventoryLocationRespository.updateDate(CommonConstant.ICABINET_PULL_Reclaimer_TIME ,sdf.format(new Date()));
//        }
        List<String> dateVo = CommonUtil.findEveryDayReload1(startTime , sdf.format(new Date()));
        if(CollectionUtil.isNotEmpty(dateVo)){
            for (String date : dateVo) {
                dataMap.put("Date1", date);
                dataMap.put("Date2", date);
                contentMap.put("Data", JSONObject.toJSONString(dataMap));
                String post = HttpUtil.post(UrlConstant.ICABINET_FEEDING_SYNC_URL, contentMap);
                if (StringUtil.isNotEmpty(post)) {
                    JSONObject jsonObject = JSONObject.parseObject(post);
                    if (jsonObject.get("success").equals(true)) {
                        Object o = jsonObject.get("data");
                        JSONArray dataArray = JSONArray.parseArray(o.toString());
                        List<Map<String, Object>> retList = new ArrayList<>();
                        for (Object oneRecordObject : dataArray) {
                            Map<String, Object> paramMap = new HashMap<>();
                            ICabinetRecordEntity iCabinetRecordEntity = new ICabinetRecordEntity();

                            JSONArray oneRecord = JSONArray.parseArray(oneRecordObject.toString());

                            QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
                            wrapper.eq("partno", oneRecord.get(7));
                            ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
                            if (ObjectUtil.isNotNull(toolForkInfoEntity)) {
                                toolForkInfoEntity.setPrice(Double.valueOf(oneRecord.get(13).toString()));
                                updateList.add(toolForkInfoEntity);
                            }

                            retList.add(paramMap);
                            iCabinetRecordEntity.setType(oneRecord.get(0).toString());
                            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                iCabinetRecordEntity.setTime(sdf1.parse(oneRecord.get(1).toString()));
                            } catch (ParseException e) {
                                throw new ParseException(e.getMessage() , 10001);
                            }
                            iCabinetRecordEntity.setOperator(oneRecord.get(2).toString());
                            iCabinetRecordEntity.setGroupName(oneRecord.get(3).toString());
                            iCabinetRecordEntity.setMachineTool(ObjectUtil.isNull(oneRecord.get(4)) ? "" : oneRecord.get(4).toString());
                            iCabinetRecordEntity.setPaper(ObjectUtil.isNull(oneRecord.get(5)) ? "" : oneRecord.get(5).toString());
                            iCabinetRecordEntity.setCraft(ObjectUtil.isNull(oneRecord.get(6)) ? "" : oneRecord.get(6).toString());
                            iCabinetRecordEntity.setPartno(oneRecord.get(7).toString());
                            iCabinetRecordEntity.setTypeName(oneRecord.get(8).toString());
                            iCabinetRecordEntity.setBrand(oneRecord.get(9).toString());
                            iCabinetRecordEntity.setPartType(oneRecord.get(10).toString());
                            iCabinetRecordEntity.setUnit(oneRecord.get(11).toString());
                            iCabinetRecordEntity.setUnitNumber(oneRecord.get(12).toString());
                            iCabinetRecordEntity.setPrice(oneRecord.get(13).toString());
                            iCabinetRecordEntity.setLocationNumber(oneRecord.get(14).toString());
                            iCabinetRecordEntity.setPcs(oneRecord.get(15).toString());
                            iCabinetRecordEntity.setNumber(oneRecord.get(16).toString());
                            insertList.add(iCabinetRecordEntity);
                        }
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(insertList)) {
            List<ICabinetRecordEntity> insert1List = new ArrayList<>();
            if(ObjectUtil.isNotNull(existICabinetRecordEntity)){
                for (ICabinetRecordEntity iCabinetRecordEntity : insertList) {
                    if(iCabinetRecordEntity.getTime().compareTo(existICabinetRecordEntity.getTime())>0){
                        insert1List.add(iCabinetRecordEntity);
                    }
                }
            }else {
                insert1List = insertList;
            }
            if (CollectionUtil.isNotEmpty(insert1List)) {
                for (int i = 0; i < 1; i++) {
                    List<ICabinetRecordEntity> subInsertList = insert1List.stream().skip(i * 600).limit(600).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(subInsertList)) {
                        iCabinetRecordMapper.insertBatchSomeColumn(insert1List);
                    }
                }
                //toolForkInfoMapper.insertBatchSomeColumn(insertList);
            }
            //iCabinetRecordMapper.insertBatchSomeColumn(insert1List);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            toolForkInfoMapper.updateBatchById(updateList);
        }
    }

    public void syncSmartICabinetData(String gtype , String time) {
        if(gtype.equals("1")){
            try {
                syncICabinetRecord(0);
            } catch (ParseException e) {
                log.error("同步加料单错误");
            }
        } else if (gtype.equals("2")) {
            try {
                syncICabinetRecord(1);
            } catch (ParseException e) {
                log.error("同步取料单错误");
            }
        }
        QueryWrapper<ICabinetRecordEntity> wrapper1 = new QueryWrapper<>();
        QueryWrapper<ConfigurationEntity> configureWrapper = new QueryWrapper<>();
        configureWrapper.eq("configure_key" , time);
        ConfigurationEntity configurationEntity1 = configurationMapper.selectOne(configureWrapper);
        List<ICabinetRecordEntity> abutmentRecords = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(gtype.equals("1")){
            abutmentRecords = icabinetRecordRepository.selectList(configurationEntity1.getConfigureValue() , new Date() , "加料单");
            inventoryLocationRespository.updateDate(CommonConstant.SYNC_ENTRY_FEED_TIME , sdf.format(new Date()));
        }else if(gtype.equals("2")){
            abutmentRecords = icabinetRecordRepository.selectList(configurationEntity1.getConfigureValue() , new Date() , "取料单");
            inventoryLocationRespository.updateDate(CommonConstant.SYNC_ENTRY_RECLAIMER_TIME , sdf.format(new Date()));
        }
        List<Integer> warehouseId = inventoryLocationRespository.selectWarehouseIds();
        syncRecordInventoryData(gtype, abutmentRecords , CommonUtil.getRandomElement(warehouseId));
    }


    public void syncRecordInventoryData(String gtype, List<ICabinetRecordEntity> abutmentRecords , Integer warehouseId) {
        if(CollectionUtil.isNotEmpty(abutmentRecords)){
            abutmentRecords.forEach(iCabinetRecordEntity -> {
                    String partno = iCabinetRecordEntity.getPartno();
                    //设置入库库位
                    List<LocationNumberVo> ids = inventoryLocationRespository.getByWarehouseIdAndPartno("A002", partno, Integer.valueOf(iCabinetRecordEntity.getNumber()));
                    if (CollectionUtil.isNotEmpty(ids)) {
                        List<LocationNumberVo> result = new ArrayList<>();
                        if(gtype.equals("1") && ObjectUtil.isNotNull(warehouseId)){
                            result = inventoryLocationService.findLocationIdAndNumber(warehouseId ,Integer.valueOf(iCabinetRecordEntity.getNumber())  , partno)
                                    .stream()
                                    .map(this::transferParam)
                                    .collect(Collectors.toList());
                        }else if(gtype.equals("2")){
                            result = findLocationNumber(ids , Integer.valueOf(iCabinetRecordEntity.getNumber()));
                        }
                        if(CollectionUtil.isNotEmpty(result)){
                            result.forEach(locationNumberVo -> {
                                InBoundOrOutBoundTimeReq inBoundOrOutBoundReq = new InBoundOrOutBoundTimeReq();
                                inBoundOrOutBoundReq.setNumber(locationNumberVo.getNumber());
                                inBoundOrOutBoundReq.setBz("");
                                inBoundOrOutBoundReq.setInventoryLocationId(locationNumberVo.getId());
                                inBoundOrOutBoundReq.setOperator(iCabinetRecordEntity.getOperator());
                                inBoundOrOutBoundReq.setPartno(partno);
                                inBoundOrOutBoundReq.setCreateTime(iCabinetRecordEntity.getTime());
                                inBoundOrOutBoundReq.setPartType(toolForkInfoRespository.selectPartTypeByPartno(partno));
                                try {
                                    if(gtype.equals("1")){
                                        inventoryLocationService.inboundLocationTool(inBoundOrOutBoundReq);
                                    }else if(gtype.equals("2")){
                                        inventoryLocationService.outboundLocationTool(inBoundOrOutBoundReq);
                                    }
                                } catch (ToolLifeCycleException e) {
                                    log.error("sync icabinet stock error =>{}" + e.getMsg() + new Date());
                                }
                            });
                        }
                    }

            });
        }
    }

    private LocationNumberVo transferParam(Map<String, Integer> stringIntegerMap) {
        LocationNumberVo locationNumberVo = new LocationNumberVo();
        locationNumberVo.setId(stringIntegerMap.get("inventoryLocationId"));
        locationNumberVo.setNumber(stringIntegerMap.get("number"));
        return locationNumberVo;
    }


//    /**
//     * 定期拉取智能柜加料单和取料单
//     */
//    @Scheduled(cron ="0 30 23 * * ? ")
//    public void inventorySnapshotTask(){
//        //每晚11点半做库存快照
//        List<ToolInventoryLocationEntity> toolInventoryLocationEntities = toolInventoryLocationMapper.selectList(new QueryWrapper<>());
//        List<ToolInventoryLocationHistoryEntity> entityList = toolInventoryLocationEntities.stream().map(this::transfrom).collect(Collectors.toList());
//        toolInventoryLocationHistoryMapper.insertBatchSomeColumn(entityList);
//    }


//    @Scheduled(cron ="0 30 23 * ? WED ")
//    public void deleteTask(){
//        List<ToolInventoryLocationEntity> toolInventoryLocationEntities = toolInventoryLocationMapper.selectList(new QueryWrapper<>());
//        List<ToolInventoryLocationHistoryEntity> entityList = toolInventoryLocationEntities.stream().map(this::transfrom).collect(Collectors.toList());
//        toolInventoryLocationHistoryMapper.insertBatchSomeColumn(entityList);
//    }

    private ToolInventoryLocationHistoryEntity transfrom(ToolInventoryLocationEntity toolInventoryLocationEntity) {
        ToolInventoryLocationHistoryEntity toolInventoryLocationHistoryEntity = new ToolInventoryLocationHistoryEntity();
        BeanUtils.copyProperties(toolInventoryLocationEntity, toolInventoryLocationHistoryEntity);
        toolInventoryLocationHistoryEntity.setSnapshotTime(new Date());
        return toolInventoryLocationHistoryEntity;
    }

    private Integer randomLocationId(List<Integer> ids) {
        Random random = new Random();
        return ids.get(random.nextInt(ids.size()));
    }

    public Object abutmentProductionReload(List<String> materialNos) {
        if(CollectionUtil.isEmpty(materialNos)){
            return Boolean.TRUE;
        }
        List<AbutmentProductionEntity> abutmentProductions = querySqlServerService.abutmentProduction(materialNos);
        if(CollectionUtil.isNotEmpty(abutmentProductions)){
            List<ProductionEntity> addProductionEntities = new ArrayList<>();
            List<ProductionEntity> updateProductionEntities = new ArrayList<>();
            List<ProcessEntity> addProcessEntities = new ArrayList<>();
            List<ProcessCraftEntity> addProcessCraftEntities = new ArrayList<>();
            List<ProductionBomEntity> addProductionBomEntities = new ArrayList<>();
            List<ProductionBomEntity> updateProductionBomEntities = new ArrayList<>();
            Map<String , ProductionEntity> productionEntityMap = new HashMap<>();
            QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
            wrapper.in("material_no" , abutmentProductions.stream().map(AbutmentProductionEntity::getMaterialNo).collect(Collectors.toList()));
            List<ProductionEntity> existProductions = productionMapper.selectList(wrapper);
            if(CollectionUtil.isNotEmpty(existProductions)){
                productionEntityMap = existProductions.stream().collect(Collectors.toMap(ProductionEntity::getMaterialNo , ProductionEntity->ProductionEntity));
            }
            for (AbutmentProductionEntity abutmentProduction : abutmentProductions) {
                String figureNo = abutmentProduction.getMaterialNo();
//                QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
//                wrapper.eq("material_no" , abutmentProduction.getMaterialNo());
//                ProductionEntity existProduction = productionMapper.selectOne(wrapper);
                ProductionEntity existProduction = productionEntityMap.get(abutmentProduction.getMaterialNo());
                if(ObjectUtil.isNotNull(existProduction) && ObjectUtil.isNotNull(existProduction.getId())){
                    //产品查询的物料bom信息不为空
                    if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProductionBom())){
                        existProduction.setProductionBomStatus(1);
                        abutmentProduction.getConnectProductionBom().forEach(abutmentProductionBomEntity -> {
                            ProductionBomEntity existProductionBomEntity = productionBomMapper.selectById(abutmentProductionBomEntity.getId());
                            if(ObjectUtil.isNotNull(existProductionBomEntity)){
                                BeanUtil.copyProperties(abutmentProductionBomEntity , existProductionBomEntity);
                                existProductionBomEntity.setFigureNo(figureNo);
                                existProductionBomEntity.setVersion(CommonConstant.INIT_VERSION);
                                updateProductionBomEntities.add(existProductionBomEntity);
                            }else{
                                ProductionBomEntity productionBomEntity = new ProductionBomEntity();
                                productionBomEntity.setCode("bom"+ UUIDUtil.getUUID());
//                            BeanUtil.copyProperties(abutmentProductionBomEntity , productionBomEntity);
                                productionBomEntity.setName(abutmentProductionBomEntity.getName());
                                productionBomEntity.setDescription(abutmentProductionBomEntity.getDescription());
                                productionBomEntity.setSeq(abutmentProductionBomEntity.getSeq());
                                productionBomEntity.setQuantity(abutmentProductionBomEntity.getQuantity().intValue());
                                productionBomEntity.setUnit(abutmentProductionBomEntity.getUnit());
                                productionBomEntity.setFigureNo(figureNo);
                                productionBomEntity.setVersion(CommonConstant.INIT_VERSION);
                                addProductionBomEntities.add(productionBomEntity);
                            }
                        });
                    }
                    updateProductionEntities.add(existProduction);
                }
            }
            //批量新增产品物料
            if(CollectionUtil.isNotEmpty(addProductionBomEntities)){
                productionBomMapper.insertBatchSomeColumn(addProductionBomEntities);
            }
            //批量修改产品物料
            if(CollectionUtil.isNotEmpty(updateProductionBomEntities)){
                productionBomMapper.updateBatchById(updateProductionBomEntities);
            }
        }
        return null;
    }
}
